package com.see.controller;
import com.common.annotation.Anonymous;
import com.common.core.controller.BaseController;
import com.common.core.domain.AjaxResult;
import com.common.core.domain.model.LoginUser;
import com.common.utils.SecurityUtils;
import com.see.core.SseEmitterManager;
import com.see.dto.SseMessageDto;
import com.see.service.SSETokenService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.MediaType;


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;


import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * SSE 控制器
 *
 * @author Lion Li
 */
@Anonymous
@RestController
@ConditionalOnProperty(value = "sse.enabled", havingValue = "true")
@RequiredArgsConstructor
public class SseController extends BaseController {

    private final SseEmitterManager sseEmitterManager;

      @Autowired
     public SSETokenService sseTokenService;


    /**
     * 建立 SSE 连接
     */
    @GetMapping(value = "${sse.path}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter connect(HttpServletRequest request) {
        //String tokenValue =SecurityUtils.getAuthentication()..getTokenValue();
        LoginUser loginUser= sseTokenService.getLoginUser(request);
        String token=sseTokenService.getToken(request);
        Long userId = loginUser.getUser().getUserId();
        return sseEmitterManager.connect(userId, token);
    }

    /**
     * 关闭 SSE 连接
     */

    @GetMapping(value = "${sse.path}/close")
    public AjaxResult close(HttpServletRequest request) {
        LoginUser loginUser= sseTokenService.getLoginUser(request);
        String token=sseTokenService.getToken(request);

        if (loginUser == null || loginUser.getUser() == null){
            return AjaxResult.success("登录信息已失效，不需要关闭连接");
        }
        Long userId = loginUser.getUser().getUserId();
        sseEmitterManager.disconnect(userId, token);
        return AjaxResult.success();
    }



}
